#!/user/bin/env python
# -*- coding: utf-8 -*-
''' 
Author: Sjy
LastEditTime: 2024-12-16 10:28:10
Description: 
'''


__all__ = []

from PyQt5 import QtCore, QtGui, QtWidgets
import gui.controls.envs as envs
import json
import uuid
import os

from .actions import Actions
from .modules import module_manager
# from .project import project_manager

class IPIMASWorkspace(envs.Dock):
    def __init__(self, params:dict={}, parent=None):
        params = {
            "objectName":"IPIMASWorkspace",
            # "title":"工具箱",
            "title":None
        }
        super(IPIMASWorkspace, self).__init__(params)
        self.__tree = None
        self.__ids = {} # 保存各个需要更新模块的id 便于快速查找到对应的widgetItem
        self.__init_ui()

        envs.ipimas_updateModelTree = lambda *args, **kwargs: self.__update_model(*args, **kwargs)
        envs.ipimas_update_modular_tree = lambda *args, **kwargs: self.__update_modular_tree(*args, **kwargs)
    def __init_ui(self) -> None:
        """初始化界面"""
        # 设置最小宽度
        extree = envs.extree
        self.setMinimumWidth(300)
        self.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        # 该属性保存停靠小部件是否可移动、可关闭和可浮动
        # self.setFeatures(QtWidgets.QDockWidget.AllDockWidgetFeatures)
        # 设置允许停靠区域
        # self.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
        tree = extree.OpTree()
        tree._start_enable_signals(["itemDoubleClicked", "customContextMenuRequested"], useAll=False)  # 只有点击需要的信号  customContextMenuRequested 关联邮件菜单
        tree._set_headers(self.__get_headers())
        # tree._add_dbclick(lambda params: self.__on_lbtn_click(params))
        # tree._add_rmenu(lambda params: self.__init_rmenu_items(params))
        self.__tree = tree
        self.set_ui(tree)
        # 初始化tree的模板结构
        self._init_tree_structure()
        # 跟新节点数据
        # self._update_model_nodes()
    def __get_headers(self) -> list:
        """获取表头"""
        return [
        {
            "title": "工作区",
            "field": "title", # 按给定的key值显示
            "type": "lable" # 缺省默认
        },
    ]
    # def __on_lbtn_click(self, params:dict={}) -> None:
    #     """点击tree事件,弹出对应修改数据界面"""
    #     triggerWidgetItem = params.get('triggerWidgetItem', None)
    #     if not triggerWidgetItem or self.__tree._is_root(triggerWidgetItem):
    #         """根节点不触发响应事件"""
    #         return
    #     col = params.get('col', 0)

    # def __init_rmenu_items(self, params:dict={}) -> None:
    #     """右键菜单事件与其他事件是有区别的,它需要构建菜单项,最后交由系统自动执行显示菜单
    #     """
    #     tempMenus = self.__tree._get_temp_rmenus() or []
    #     tempMenus = [ # 要返回右键菜单项
    #         *tempMenus,
    #         {
    #             "title":"导入数据",
    #             # "action":lambda:Actions().import_json()
    #         },
    #         {
    #             "title":"导出数据",
    #             # "action":lambda:Actions().export_json()
    #         },
    #     ]
    #     self.__tree._set_temp_rmenus(tempMenus)
    def _init_tree_structure(self) -> None:
        """初始化树数据"""
        self.__ids = {
            "mainModel":  uuid.uuid4(),
            "subModels":  uuid.uuid4(),
            "resultModels":  uuid.uuid4(),
        }
        data = [
            # {
            #     "title":"工程",
            #     "children":[
            #         # {
            #         #     "title": "主模型", 
            #         #     "scope":True, # 不需要事件向上冒泡
            #         #     "id": self.__ids.get("mainModel"),
            #         #     "children":[],
            #         #     "events":{
            #         #         "rmenu":  lambda params: self.__init_model_rmenu(params),
            #         #         "dbClick":  lambda params: self.__init_model_dbclick(params)
            #         #     },
            #         # },
            #         {
            #             "title": "参数设置",
            #             "children":[
            #                 {
            #                     "title":"参数化建模",
            #                     "name":"mathParamOpt",
            #                     "events":{
            #                         "dbClick":  lambda params: Pops.show_dlg(flag="paramsModeling")
            #                     },
            #                 },
            #                 {
            #                     "title": "材料属性设置",
            #                     "events": {
            #                         "dbClick": lambda params: Pops.show_dlg(
            #                             flag="materialSetting"
            #                         )
            #                     },
            #                 },
            #                 {
            #                     "title":"网格划分",
            #                     "events":{
            #                         "dbClick":  lambda params: Pops.show_dlg(flag="meshPartition")
            #                     },
            #                 },
                            
            #                 {
            #                     "title":"载荷与边界条件",
            #                     "events":{
            #                         "dbClick":  lambda params: Pops.show_dlg(flag="loadBoundary")
            #                     },
            #                 },
            #                 {
            #                     "title":"优化方法",
            #                     "name":"loadBoundaryOpt",
            #                     "events":{
            #                         "dbClick":  lambda params: Pops.show_dlg(flag="optimizationMethod")
            #                     },
            #                 },{
            #                     "title":"后处理",
            #                     "name":"postOpt",
            #                     "events":{
            #                         "dbClick":  lambda params: Pops.show_dlg(flag="postProcessing")
            #                     },
            #                 },
            #             ]
            #         },
                    
            #         {
            #             "title": "低周疲劳约束",
            #             "children":[
            #                 {
            #                     "title":"导入模型",
            #                     "name":"lowImportModel",
            #                     "events":{
            #                         "dbClick":  lambda params: Pops.show_dlg(flag="analysisModeling")
            #                     },
            #                 },
            #                 {
            #                     "title": "寿命分析",
            #                     "events": {
            #                         "dbClick": lambda params: Pops.show_dlg(flag="lifeAnalysis")
            #                     },
            #                 },
            #                 {
            #                     "title":"材料属性",
            #                     "events":{
            #                         "dbClick":  lambda params: Pops.show_dlg(flag="materialsProperties")
            #                     },
            #                 },
            #                 {
            #                     "title":"显示结果",
            #                     "events":{
            #                         "dbClick":  lambda params: Pops.show_dlg(flag="lowShowResult")
            #                     },
            #                 },
            #             ]
            #         },
            #         {
            #             "title": "DFR 疲劳分析",
            #             "events":{
            #                 "dbClick":  lambda params: Pops.show_dlg(flag="dfr_analysis")
            #             },
            #         }
            #         # {
            #         #     "title": "计算模型",
            #         #     "scope":True, # 不需要事件向上冒泡
            #         #     "id": self.__ids.get("subModels"),
            #         #     "events":{
            #         #         "rmenu":  lambda params: self.__init_submodel_rmenu(params),
            #         #         "dbClick":  lambda params: self.__init_submodel_dbclick(params)
            #         #     },
            #         #     "children":[
            #         #     ]
            #         # },
            #         # {
            #         #     "title": "结果模型",
            #         #     "id": self.__ids.get("resultModels"),
            #         #     "events":{
            #         #         "rmenu":  lambda params: self.__init_resultmodel_rmenu(params),
            #         #         "rmenu":  lambda params: self.__init_resultmodel_dbclick(params)
            #         #     },
            #         #     "children":[
            #         #     ]
            #         # }
                    
            #     ],
            # }
        ]
        self.__tree._set_data(data)
    def _update_model_nodes(self) -> None:
        """更新子节点"""
        self.__update_model("mainModel")

    def __get_main_childs(self) -> list:
        """获取主模型子节点"""
        childs = []
        data = Actions.get_data()
        mainModel = data.get("mainModel", "")
        mainModelCalFile = data.get("mainModelCalFile", "")
        if mainModel:
            title = mainModel and  os.path.basename(mainModel) or ''
            childs.append({
                "title": f"模型文件：{title}",
                "data":{
                    "file": mainModel,
                    "type":"inp",
                }
            }) 
            title = mainModelCalFile and  os.path.basename(mainModelCalFile) or ''
            childs.append({
                "title": f"计算文件：{title}",
                "data":{
                    "file": mainModelCalFile,
                    "type":"file",
                }
            }) 
        return childs

    # 事件 ========================================
    # def __init_submodel_rmenu(self, params) -> None:
    #     """菜单"""
    #     # 如果是子节点 则弹出删除，编辑菜单
    #     isBranch = params.get("triggerItemIsBranch", False)
    #     if isBranch:
    #         params.get("otree")._set_temp_rmenus([
    #             {
    #                 "title":"添加计算模型",
    #                 "action":lambda:Pops.import_submodel()
    #             },
    #         ])
    #     else:
    #         params.get("otree")._set_temp_rmenus([
    #             {
    #                 "title":"修改计算参数",
    #                 "action":lambda:print("设置参数")
    #             },
    #             {},
    #             {
    #                 "title":"删除",
    #                 "action":lambda:print("删除")
    #             },
    #             {},
    #             {
    #                 "title":"显示模型",
    #                 "action":lambda params=params:self.__open_model_node(params)
    #             },
    #         ])  
    # def __init_resultmodel_rmenu(self, params) -> None:
    #     """菜单"""
    #     # 如果是子节点 则弹出删除，编辑菜单
    #     isBranch = params.get("triggerItemIsBranch", False)
    #     if isBranch:
    #         params.get("otree")._set_temp_rmenus([
    #             {
    #                 "title":"添加结果模型",
    #                 "action":lambda:print("添加结果模型")
    #             },
    #         ])
    #     else:
    #         params.get("otree")._set_temp_rmenus([
    #             {
    #                 "title":"设置参数",
    #                 "action":lambda:print("设置参数")
    #             },
    #             {},
    #             {
    #                 "title":"编辑",
    #                 "action":lambda:print("编辑")
    #             },
    #             {},
    #             {
    #                 "title":"删除",
    #                 "action":lambda:print("删除")
    #             },
    #         ]) 
    # def __init_model_rmenu(self, params) -> None:
    #     isBranch = params.get("triggerItemIsBranch", False)
    #     if isBranch:
    #         params.get("otree")._set_temp_rmenus([
    #             {
    #                 "title":"导入模型",
    #                 "action":lambda:Pops.import_main_model()
    #             },
    #         ])
    #     else:
    #         params.get("otree")._set_temp_rmenus([
    #             {
    #                 "title":"打开",
    #                 "action":lambda :self.__open_main_model_file(params)
    #             },
    #         ])
    # def __init_model_dbclick(self, params) -> None:
    #     """双击主模型事件"""
    #     # 主模型双击事件
    #     isBranch = params.get("triggerItemIsBranch", False)
    #     if isBranch: return Pops.import_main_model()
    #     self.__open_main_model_file(params)
    # def __open_main_model_file(self, params:dict={}) -> None:
    #     """打开主模型下的文件，模型直接打开，其他类型的则调用系统命令打开"""
    #     widgetItem = params.get("triggerWidgetItem", None)
    #     userData = self.__tree._get_widgetitem_data(widgetItem)
    #     if not self.__open_model_node(params):
    #         # 文件则从系统中打开文件
    #         Actions.open_file(userData.get("file", ""))
    # def __open_model_node(self, params:dict={}):
    #     widgetItem = params.get("triggerWidgetItem", None)
    #     userData = self.__tree._get_widgetitem_data(widgetItem)
    #     curType = userData.get("type", "")
    #     if curType == "inp": 
    #         """如果是 模型则需要显示模型"""
    #         Actions.show_inp(userData.get("file", ""))
    #         return True  # 打开成功
    #     return False
    # def __init_submodel_dbclick(self, params) -> None:
    #     """子模型双击事件"""
    #     isBranch = params.get("triggerItemIsBranch", False)
    #     if isBranch: return Pops.import_submodel()
    #     # 如果是子模型则设置对应参数
    #     # self.__edit_submodle(params)
    #     # self.__open_sub_model(params)
    # def __init_resultmodel_dbclick(self, params) -> None:
    #     """结果模型双击事件"""
    #     isBranch = params.get("triggerItemIsBranch", False)
    #     if isBranch: return Pops.import_result_model()
        # 如果是子模型则设置对应 展示预览图片
    def __update_model(self, key) -> None:
        if key == "mainModel":
            mainModelWidgetItem = self.__tree._get_widget_item('id', self.__ids.get("mainModel"))
            childs = self.__get_main_childs()
            self.__update_tree_nodes(mainModelWidgetItem, childs)
        elif key == "subModels":
            subModelWidgetItem = self.__tree._get_widget_item('id', self.__ids.get("subModels"))
            childs = self.__get_sub_childs("subModels")
            self.__update_tree_nodes(subModelWidgetItem, childs)
        elif key == "resultModels":
            resultModelWidgetItem = self.__tree._get_widget_item('id', self.__ids.get("resultModels"))
            childs = self.__get_sub_childs("resultModels")
            self.__update_tree_nodes(resultModelWidgetItem, childs)
    def __get_sub_childs(self, name) -> list:
        """获取子模型子节点"""
        childs = []
        data = Actions.get_data()
        subModels = data.get(name, [])
        for item in subModels:
            childs.append({
                "title": item.get("title", ""),
                "data": item
            })
        return childs
    def __update_tree_nodes(self, widgetItem:str=None, childs:list=[]) -> None:
        """更新树节点"""
        isExpanded = widgetItem.isExpanded()
        self.__tree._init_tree_items(childs, widgetItem)
        if isExpanded:
                widgetItem.setExpanded(True)
    

    # 这个是根据当前菜单内容 更新dock 显示的信息
    def __update_modular_tree(self, params:dict={}) -> None:
        """更新模块树"""
        module_manager.init_dock(self.__tree, params)

# 日志 dock
class IPIMASLog(envs.Dock):
    def __init__(self, params:dict={}, parent=None):
        params = {
            "objectName":"IPIMASLog",
            "title":None,
            "pos": QtCore.Qt.BottomDockWidgetArea,
        }
        super(IPIMASLog, self).__init__(params)
        self.setFeatures(QtWidgets.QDockWidget.AllDockWidgetFeatures)  # 禁用所有特性，包括标题栏
        self.setTitleBarWidget(QtWidgets.QLabel("日志"))  # 设置一个空的 QWidget 作为标题栏
        self.setMinimumHeight(80)
        self.__init_ui()

        envs.ipimas_toLog = lambda *args, **kwargs: self.update_log(*args, **kwargs)
        envs.ipimas_clearLog = lambda *args, **kwargs: self.plainTextEdit.clear()
        envs.ipimas_getLog = lambda *args, **kwargs: self.plainTextEdit.toPlainText()
    def __init_ui(self):
        """初始化界面"""
        self.plainTextEdit = QtWidgets.QPlainTextEdit()
        self.set_ui(self.plainTextEdit)
        # 注册关联函数
    def update_log(self, log, *args, **kwargs):
        # 将 *args 参数内容 转成完成字符串 
        # if "number of iterations" in log:
        #     return 
        # elif "amplitude" in log:
        #     return 
        # elif "Over,The load amplitude is" in log:
        #     return 
        log = log + " ".join([str(i) for i in args or []])
        # print("log=", log)
        self.plainTextEdit.appendPlainText(log)
        self.plainTextEdit.moveCursor(QtGui.QTextCursor.End)
        self.plainTextEdit.ensureCursorVisible()
        QtWidgets.QApplication.processEvents()